//
//  AlbumPictureViewController.m
//  album
//
//  Created by 云天 李 on 12-1-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AlbumPictureViewController.h"
#import "AlbumDB.h"
#import "Album.h"
#import "Picture.h"
#import "AlbumHelper.h"
#import "MsgBoxHelper.h"

@implementation AlbumPictureViewController

@synthesize currentPicture = _currentPicture;
@synthesize pictures = _pictures;
@synthesize scrollView = _scrollView;
@synthesize currentPage = _currentPage;
@synthesize ignoreUIScrollViewDelegate = _ignoreUIScrollViewDelegate;

@synthesize autoscrollTimer = _autoscrollTimer;

// 设置标题
- (void)setNavigationBarTitle
{
    self.title = [NSString stringWithFormat:@"第 %i 张（共 %i 张）", self.currentPage, [self.pictures count]];
}

// 从数据库读取当前相册下的所有图片
- (void) loadPictures
{
    if (self.pictures == nil)
    {
        self.pictures = [NSMutableArray array];
    }
    else
    {
        [self.pictures removeAllObjects];
    }
    
    self.pictures = [AlbumDB fetchPictures:self.currentPicture.albumid];
}

// 载入图片至ScrollView
- (void)loadPicturesToScrollView
{
	// 视图背景色
    [self.view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
    
	// 以下设置可以在 Interface Builder 中进行修改。
	[self.scrollView setBackgroundColor:[UIColor blackColor]];
	[self.scrollView setCanCancelContentTouches:NO];
	[self.scrollView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
    //缺省是NO，不过我们希望在ScrollView中进行绘制
	[self.scrollView setClipsToBounds:YES];
	// 可以滚动
	[self.scrollView setScrollEnabled:YES];
    // 缺省是NO，设置为YES后，scroller在每张图滚动后暂停，就像iPhone的主屏幕滚动那样。
    // 读者可以设置为NO试一试。
	[self.scrollView setPagingEnabled:YES];
	
	// 载入图片至ScrollView
	Picture *_picture = nil;
    CGFloat curXLoc = 0;
	for (_picture in self.pictures)
	{
        NSString *pictureName = [AlbumHelper pictureFilePath:[NSString stringWithFormat:@"%@", _picture.picturename] withAlbum:_picture.albumid];
		UIImage *image = [UIImage imageWithContentsOfFile:pictureName];
		UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        CGRect rect = [[UIScreen mainScreen] bounds];
        rect.size.height = rect.size.height;
        rect.origin = CGPointMake(curXLoc, rect.origin.y - 44.0);
		imageView.frame = rect;

		[self.scrollView addSubview:imageView];
		[imageView release];
        
        curXLoc += rect.size.width;
	}
	
	// 设置ScrollView的内容尺寸，以便能滚动
	[self.scrollView setContentSize:CGSizeMake((self.pictures.count * [self.scrollView bounds].size.width), [self.scrollView bounds].size.height)];
}

//  点击工具栏的左侧 按钮，显示一个动作列表
- (IBAction) shareAction:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"用电子邮件发送照片", @"保存到照片库", nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	// 使第一个按钮变成红色
    actionSheet.destructiveButtonIndex = 0;
    // 从底部升起
	[actionSheet showInView:self.view];
	[actionSheet release];
    
    // 停止幻灯片播放
    [self stopAutoscroll];
}

//  点击工具栏的右侧 按钮，用于幻灯片播放图片
- (IBAction) playAction:(id)sender
{	
    [self autoScrollPictures];
}

// 图片保存到系统照片库后，信息提示
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
	NSString *msg = error ? [NSString stringWithFormat:@"%@\n%@", @"保存失败，请稍后重试。", [error description]] : @"保存成功";
	
    [MsgBoxHelper showMsgBoxOK:msg fromDeleate:self];
}

// 将当前图片保存到系统照片库
- (void) saveToSystemAlbum
{	
    NSString *pictureName = [AlbumHelper pictureFilePath:[NSString stringWithFormat:@"%@", self.currentPicture.picturename] withAlbum:self.currentPicture.albumid];
    UIImage *image = [UIImage imageWithContentsOfFile:pictureName];

    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

#pragma mark - Scroll Picture
// 滚动多少页
- (void) scrollPages: (NSUInteger)withPage
{
    CGPoint offset = self.scrollView.contentOffset;
    float viewWidth = [[UIScreen mainScreen] bounds].size.width;
	
	if (offset.x + viewWidth * withPage < self.scrollView.contentSize.width)
	{
		CGPoint newOffset = CGPointMake(offset.x + viewWidth * withPage, offset.y);
		[self.scrollView setContentOffset:newOffset animated:YES];
	}

}

#pragma mark - ScrollView delegate methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.ignoreUIScrollViewDelegate)
    {
        self.ignoreUIScrollViewDelegate = NO;
        return;
    }
    
    // 计算当前显示第几页
    float viewWidth = [[UIScreen mainScreen] bounds].size.width;
    CGRect visibleBounds = scrollView.bounds;

    // 当前页码的左上顶点X值
    float currentPageX = viewWidth * (self.currentPage - 1);
    int pageIndex = 0;
    if (CGRectGetMinX(visibleBounds) < currentPageX)
    {
        pageIndex = floorf((CGRectGetMinX(visibleBounds) + viewWidth / 2) / CGRectGetWidth(visibleBounds));
    }
    else
    {
        pageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    }
    self.currentPage = MAX(pageIndex, 0) + 1;


    // 设置标题
    [self setNavigationBarTitle];
    
    // 当前显示的图片
    [self setCurrentPicture:[self.pictures objectAtIndex:self.currentPage - 1]];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// 用电子邮件发送照片
	if (buttonIndex == 0)
	{
        Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
        
        if (mailClass != nil)
        {
            if ([mailClass canSendMail])
            {
                [self displayComposerSheet];
            }
            else
            {	
                [MsgBoxHelper showMsgBoxOK:@"当前设备不支持发送邮件。" fromDeleate:self];
                
            }
        }
        else
        {
            [MsgBoxHelper showMsgBoxOK:@"当前设备不支持发送邮件。" fromDeleate:self];
        }
        
		[self displayComposerSheet];
	}    // 保存到系统照片库
    else if (buttonIndex == 1)
    {
        [self saveToSystemAlbum];
    }
    // 取消
    else
    {
        // 忽略
    }
}

#pragma mark MFMailComposeViewControllerDelegate
// 显示发送邮件界面
- (void)displayComposerSheet
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	/*
	// 主题
	[picker setSubject:@"漂亮的图片"];
	
	// 收件人/抄送/密送
	NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"]; 
	NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil]; 
	NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"]; 
	
	[picker setToRecipients:toRecipients];
	[picker setCcRecipients:ccRecipients];	
	[picker setBccRecipients:bccRecipients];
	
	// 正文
	NSString *emailBody = @"It is raining in sunny California!";
	// 正文是否是HTML格式
	[picker setMessageBody:emailBody isHTML:NO];
	*/
	
	// 附件
    NSString *pictureName = [AlbumHelper pictureFilePath:[NSString stringWithFormat:@"%@", self.currentPicture.picturename] withAlbum:self.currentPicture.albumid];
    NSData *myData = [NSData dataWithContentsOfFile:pictureName];
	[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"attach"];
	
	[self presentModalViewController:picker animated:YES];
    
	[picker release];
}

// 电子邮件发送结果
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{	
	NSString *msg = nil;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			//msg = @"Result: canceled";
			break;
		case MFMailComposeResultSaved:
			msg = @"邮件已经保存。";
			break;
		case MFMailComposeResultSent:
			msg = @"邮件已经发送。";
			break;
		case MFMailComposeResultFailed:
			msg = @"邮件发送失败，请稍后重试。";
			break;
		default:
			msg = @"邮件未发送，请检查您的网络是否连接。";
			break;
	}
    
	[self dismissModalViewControllerAnimated:YES];
	
	if (msg != nil)
    {
        [MsgBoxHelper showMsgBoxOK:msg fromDeleate:self];
	}
}

// 工具栏上的播放、暂停按钮
- (UIBarButtonItem *)createToolbarPlayItem:(UIBarButtonSystemItem)item
{
	UIBarButtonItem *playItem = [[[UIBarButtonItem alloc] 
                                  initWithBarButtonSystemItem:item
                                  target:self
                                  action:@selector(playAction:)] 
                                 autorelease];
    return playItem;
}

#pragma mark - Autoscrolling methods
// 自动滚动图片
- (void)autoScrollPictures
{
    if (nil == self.autoscrollTimer)
    {
		
		[self changePlayItemTo:UIBarButtonSystemItemPause];
        // 隐藏后退按钮
        self.navigationItem.hidesBackButton = YES;
		
		self.autoscrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                                target:self 
                                                              selector:@selector(autoscrollTimerFired:) 
                                                              userInfo:nil
                                                               repeats:YES];
	}
	else
    {
		[self stopAutoscroll];
	}
}


// 自动播放时，更改按钮图片
- (void)changePlayItemTo:(UIBarButtonSystemItem)item
{
	NSMutableArray *tbItems = [[NSMutableArray arrayWithArray:self.toolbarItems] retain];
    
	UIBarButtonItem *playItem = [self createToolbarPlayItem:item];
    
	[tbItems replaceObjectAtIndex:2 withObject:playItem];
	self.toolbarItems = tbItems;
	[tbItems release];
}

// 开始播放
- (void)autoscrollTimerFired:(NSTimer*)timer
{
    //  滚动1页
	[self scrollPages:1];
    
	// 当到最后一张时，停止自动播放
	if (self.scrollView.contentOffset.x + 2 * [[UIScreen mainScreen] bounds].size.width >= self.scrollView.contentSize.width)
	{
		[self stopAutoscroll];
	}
    
}

// 停止播放
- (void)stopAutoscroll
{
    if (nil != self.autoscrollTimer)
    {
        [self.autoscrollTimer invalidate];
        self.autoscrollTimer = nil;
        
        [self changePlayItemTo:UIBarButtonSystemItemPlay];
        
        // 显示后退按钮
        self.navigationItem.hidesBackButton = NO;
    }
}

#pragma mark - init
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)dealloc
{
    [_currentPicture release];
    [_pictures release];
    [_scrollView release];
    [_autoscrollTimer release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 添加工具栏按钮
    UIBarButtonItem *shareButtonItem = [[[UIBarButtonItem alloc]  
                                         initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                         target:self   
                                         action:@selector(shareAction:)]
                                        autorelease];
	UIBarButtonItem *flexItem = [[[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                  target:nil
                                  action:nil]
                                 autorelease];
	UIBarButtonItem *playButtonItem = [self createToolbarPlayItem:UIBarButtonSystemItemPlay];
    
    self.toolbarItems = [NSArray arrayWithObjects: shareButtonItem, flexItem, playButtonItem, nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 忽略UIScrollViewDelegate
    self.ignoreUIScrollViewDelegate = YES;
    
    // 载入图片
    [self loadPictures];
    [self loadPicturesToScrollView];
    
    // 设置标题
    [self setNavigationBarTitle];
    
    // 滚动到指定页码
    self.scrollView.contentOffset = CGPointMake(0, 0);
    [self scrollPages:self.currentPage - 1];
	
	// 显示工具栏
    [self.navigationController setToolbarHidden:NO];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
